package com.yld.car.market;

import java.io.File;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.UserInfo;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MoreActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more);

		TextView titleText = (TextView) findViewById(R.id.title);
		// 设置标题
		titleText.setText(R.string.main_more);
		list1 = (ListView) findViewById(R.id.list1);
		list2 = (ListView) findViewById(R.id.list2);
		list3 = (ListView) findViewById(R.id.list3);

		list1.setOnItemClickListener(listItemClickListenerOne);
		list2.setOnItemClickListener(listItemClickListenerTwo);
		list3.setOnItemClickListener(listItemClickListenerThree);
		this.list1Data = new ArrayList<String>();
		this.list1Data.add("推送通知");
		this.list1Data.add("清除缓存");
		this.list2Data = new ArrayList<String>();
		this.list2Data.add("版本号");
		this.list2Data.add("意见反馈");
		this.list3Data = new ArrayList<String>();
		this.list3Data.add("推荐给好友");
		this.list3Data.add("关于我们");

		int[] idsOne = { R.drawable.more_receiver_notification,
				R.drawable.more_clear_cache };

		int[] idsTwo = { R.drawable.more_current_version,
				R.drawable.more_feed_back };

		int[] idsThree = { R.drawable.more_shared_friends,
				R.drawable.more_about_i_car_market };
		SimpleListAdapter adapter = new SimpleListAdapter(list1Data, this,
				idsOne);
		list1.setAdapter(adapter);
		adapter = new SimpleListAdapter(list2Data, this, idsTwo);
		list2.setAdapter(adapter);

		adapter = new SimpleListAdapter(list3Data, this, idsThree);
		list3.setAdapter(adapter);

		Button logout = (Button) findViewById(R.id.logoutButton);

		logout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				File f = MoreActivity.this.getFileStreamPath("userInfo");
				System.out.println(f.delete());

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(),
						GuidePageActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				showDialogFinish("您确定退出吗？", intent);

			}
		});
	}

	// 定义ListView控件，用于设置
	private ListView list1, list2, list3;

	private List<String> list1Data;
	private List<String> list2Data;
	private List<String> list3Data;

	private class SimpleListAdapter extends BaseAdapter {

		private List listData;
		private Context mContext;
		private LayoutInflater mLayoutInflater;

		private int[] ids;

		public SimpleListAdapter(List listData, Context context, int[] ids) {
			this.listData = listData;
			this.mContext = context;
			this.mLayoutInflater = LayoutInflater.from(mContext);
			this.ids = ids;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				convertView = mLayoutInflater.inflate(
						R.layout.more_base_list_items_simple, null);
			}

			ImageView image = (ImageView) convertView.findViewById(R.id.image);
			image.setImageResource(ids[position]);
			((TextView) convertView.findViewById(R.id.itemContent))
					.setText((CharSequence) this.listData.get(position));
			((ImageView) convertView.findViewById(R.id.nextStep))
					.setVisibility(0);
			convertView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return convertView;
		}

		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return super.isEnabled(position);
		}

	}

	private OnItemClickListener listItemClickListenerOne = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			// TODO Auto-generated method stub

			if (0 == position) {

				// Intent intent = new Intent();
				// intent.setClass(MoreActivity.this, FindDealerActivity.class);
				// startActivity(intent);
				// Toast.makeText(MoreActivity.this, "推送通知....",
				// Toast.LENGTH_SHORT).show();

				// settingMsgPush().show();
				bindAliasPushMsg();
			} else if (1 == position) {

				boolean issuccess = clearCache();
				String tmp = "";
				if (issuccess) {
					tmp = "成功清除缓存信息";
				} else {
					tmp = "清除失败";
				}
				Toast.makeText(MoreActivity.this, tmp, Toast.LENGTH_SHORT)
						.show();
				// Intent intent = new Intent();
				// intent.setClass(MoreActivity.this, RecentViewActivity.class);
				// startActivity(intent);
			}

		}
	};

	private OnItemClickListener listItemClickListenerTwo = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			// TODO Auto-generated method stub

			if (0 == position) {
				// Intent intent = new Intent();
				// intent.setClass(MoreActivity.this,
				// UpdatePasswordActivity.class);
				// startActivity(intent);
				// finish();

				String versionName = null;
				;
				try {
					versionName = getVersionName();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					versionName = "未知";
				}
				Toast.makeText(MoreActivity.this, "当前应用版本为：" + versionName,
						Toast.LENGTH_SHORT).show();
			} else if (1 == position) {
				Intent intent = new Intent();
				intent.setClass(MoreActivity.this, FeedBackActivity.class);
				startActivity(intent);
				// Toast.makeText(MoreActivity.this,
				// "帮助中心正在建设中，如任何疑问请致电客服：15823912195", Toast.LENGTH_SHORT)
				// .show();
			}

		}
	};

	private OnItemClickListener listItemClickListenerThree = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			// TODO Auto-generated method stub

			// Intent intent = new Intent();
			// intent.setClass(MoreActivity.this, UpdatePasswordActivity.class);
			// startActivity(intent);

			if (0 == position) {

				// Toast.makeText(MoreActivity.this, "推荐给好友....",
				// Toast.LENGTH_SHORT).show();
				// finish();

				Intent intent = new Intent(MoreActivity.this,
						MoreShareActivity.class);
				startActivity(intent);

			}

			if (1 == position) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MoreActivity.this);
				builder.setTitle("爱车行");

				builder.setMessage("感谢您使用我们的产品，你的满意，更是我们的动力，关注爱车行，关注您的爱车！");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});
				builder.create().show();
			}
		}
	};

	/**
	 * 获取当前应用的版本号：
	 * 
	 * @return
	 * @throws Exception
	 */

	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		String version = packInfo.versionName;
		return version;
	}

	/**
	 * 清除缓存
	 * 
	 * @return
	 */
	private boolean clearCache() {
		File f = new File(PublishCarPickPhotoActivity.IMG_CACHE_PATH);
		try {
			deleteAll(f);
			return true;
		} catch (Exception e) {

			e.printStackTrace();
			return false;
		}

	}

	// 递归删除指定路径下的所有文件
	private static void deleteAll(File file) {
		if (file.isFile() || file.list().length == 0) {
			file.delete();
		} else {
			File[] files = file.listFiles();
			for (File f : files) {
				deleteAll(f);// 递归删除每一个文件
				f.delete();// 删除该文件夹
			}
		}
	}

	private AlertDialog settingMsgPush() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		View v = LayoutInflater.from(this).inflate(R.layout.setting_msg_push,
				null);
		builder.setView(v);
		// 设置标题
		builder.setTitle("别名设置");

		final EditText aliasText = (EditText) v.findViewById(R.id.aliasText);
		// 设置提交和重置按钮

		final Button submitBtn = (Button) v.findViewById(R.id.submitBtn);

		final Button resetBtn = (Button) v.findViewById(R.id.resetBtn);

		final AlertDialog dialog = builder.create();

		submitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				final String alias = aliasText.getText().toString();

				if (alias != null && alias.trim().length() != 0) {
					new Thread(new Runnable() {
						public void run() {
							JPushInterface.setAliasAndTags(
									getApplicationContext(), alias, null,
									mAliasCallback);
						}
					}).start();

					dialog.dismiss();

				} else {
					Toast.makeText(getApplicationContext(), "别名不能为空",
							Toast.LENGTH_SHORT).show();

				}

			}
		});
		resetBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				aliasText.setText("");
			}
		});
		return dialog;
	}

	private static final String TAG = MoreActivity.class.getName();
	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

		@Override
		public void gotResult(int code, final String alias, Set<String> tags) {
			String logs;
			switch (code) {
			case 0:
				logs = "Set tag and alias success" + tags;
				Log.i(TAG, logs);
				break;

			case 6002:
				logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
				Log.i(TAG, logs);
				if (NetworkProgressUtils.getInstance().getAPNType(
						getApplicationContext()) != -1) {

					new Thread(new Runnable() {
						public void run() {
							JPushInterface.setAliasAndTags(
									getApplicationContext(), alias, null,
									mAliasCallback);
						}
					}).start();
				} else {
					Log.i(TAG, "No network");
				}
				break;

			default:
				logs = "Failed with errorCode = " + code;
				Log.e(TAG, logs);
			}

			// ExampleUtil.showToast(logs, getApplicationContext());
		}

	};

	private void bindAliasPushMsg() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				UserInfo u = (UserInfo) readObject("userInfo");

				String currentDealerId = u.getUserId();

				HashMap<String, String> allParams = new HashMap<String, String>();

				allParams.put("userId", currentDealerId);

				NetworkProgressUtils utils = NetworkProgressUtils.getInstance();

				Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
						ConstantUtils.ALL_METHROD_NAME.get(50),
						ConstantUtils.NAME_SPACE
								+ ConstantUtils.ALL_METHROD_NAME.get(50),
						ConstantUtils.SEND_MESSAGE_FOR_ANDROID_TO_BUTTON_URL,
						allParams);

				 //System.out.println("send--->"+o);
				int index = o.toString().indexOf("获取别名成功，别名为:");
				if (index >= 0) {

					String replace = o.toString().substring(index + 11,
							o.toString().length() - 2);

					System.out.println("tag----"+replace);
					//String alias[] = replace.split(",");

					/*Set<String> tags=new HashSet<String>();
					
					for (String string : alias) {
						tags.add(string);
					}*/
				/*	for (int i = 0; i < alias.length; i++) {
						// 注册别名时10s内只能注册三个，因此要休眠
						if (i > 0 && (i % 3 == 0)) {
							try {
								Thread.sleep(11000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}*/
						// JPushInterface.setAliasAndTags(getApplicationContext(),
						// alias[i], null, mAliasCallback);

						//JPushInterface.setTags(getApplicationContext(),
								//alias[i], mAliasCallback);
					//JPushInterface.setTags(getApplicationContext(), tags, mAliasCallback);
					
					//}

					allParams = new HashMap<String, String>();

					allParams.put("alias", replace);

					o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(51),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME.get(51),
							ConstantUtils.SEND_MESSAGE_FOR_ANDROID_URL,
							allParams);

					System.out.println(o);
				}
			}
		}).start();

	}
}
